package esiag.pds.receivers;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import esiag.pds.beans.HostProvider;
import esiag.pds.contextManagement.Context;
import esiag.pds.interfaces.IContextProvider;
import esiag.pds.interfaces.IHostProvider;
import esiag.pds.interfaces.IgetContext;

public class ReplicationReceiver extends Thread{

   		 IgetContext rmiServer;
		 IContextProvider contextProvider;
		 IHostProvider hostprovider;
		
		 Registry registry;
		 int port=9090;
		 
	     Context context;	 
	
	public ReplicationReceiver() {
		// TODO Auto-generated constructor stub
		context=new Context();
		hostprovider=new HostProvider();
	}
	
	public void start(int frequency){	
		try {
			while(true){
				  Thread.sleep(frequency);
				  context=rmiWork();
				  System.out.println(context);	
				  if(contextProvider!=null)
						  contextProvider.setContext(context.getTab());				 
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
	}

	public Context rmiWork(){
		
		System.out.println("Receiving from " +hostprovider.getHost()+ ":" + port);
		  try{
			  registry=LocateRegistry.getRegistry(hostprovider.getHost(),port);
			  rmiServer=(IgetContext)registry.lookup("Server03");
			  // call the remote method
			  return rmiServer.getContext();			
		  }  catch(Exception e){
			  e.printStackTrace();
			  return null;
		  }
	}
	
	public Context getContext(){
		return context;
	}
}
